<?php

namespace app\astrologer\controller\v3;


use app\aliyun\controller\AliyunFilterWord;
use app\astrologer\controller\AstrAuth;
use app\common\cachemodel\Orders;
use app\common\cachemodel\zlcr2\Zlcr2AstrTasks;
use app\common\cachemodel\zlcr2\Zlcr2QuestionUserView;
use app\common\cachemodel\zlcr2\Zlcr2UserAddQuestion;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\ZlcrAppeal;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrMessage;
use app\common\lib\Push;
use app\common\lib\Util;
use app\common\model\MessageCenter;
use app\common\model\Recode;
use app\common\model\User;
use think\Log;

class Question extends AstrAuth
{
    /**
     * 问答补充回复
     */
    public function supplementAnswer()
    {
        $taskId = input('task_id/d', '');
        $type = input('type/d', 0); //回答类型【1=>语音,2=>文字】
        $content = trim(input('content/s', ''));    //答案内容【语音回答为视频地址】
        $duration = input('duration/d', 0);
        $flag = input('flag/d', 0);

        if (empty($content))
        {
            return show(config('code.error'), '答案不能为空');
        }

        if (Util::commentCheck($this->astrInfo['id'], ['type' => $type, 'content' => $content, 'duration' => $duration, 'flag' => $flag, 'task_id' => $taskId], 10))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }

        if (!in_array($flag, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        //阿里检测
        if ($type === 2)
        {
            $res = AliyunFilterWord::checkText($content, 'question_astro');
            if ($res)
            {
                return show(config('code.error'), '当前回复中有违规词汇请重新核实');
            }
        }

        $astrTaskModel = new Zlcr2AstrTasks();
        $zlcrAppealModel = new ZlcrAppeal();

        $taskInfo = $astrTaskModel->getInfoById($taskId);
        if (!$taskInfo || $taskInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常，问题不存在');
        }

        if ($taskInfo['status'] !== 1)
        {
            return show(config('code.error'), '任务状态异常，请稍后再试～');
        }

        $qid = $taskInfo['qid'];

        $questionModel = new Zlcr2UserQuestion();
        $addQuestionModel = new Zlcr2UserAddQuestion();

        $questionInfo = $questionModel->getInfoById($qid, []);
        if ($questionInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常，问题不存在');
        }

        if (!in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '答案类型异常，请稍后再试～');
        }

        $asnwerType = 0;
        if ($flag === 1)
        {
            // 补充回答
            if ($questionInfo['reply_time'] + 3600 < $this->request->time())
            {
                return show(config('code.error'), '已超过可补充时限，请重新加载页面');
            }
            if ($questionInfo['status'] !== 5 || $questionInfo['complain_status'] === 1)
            {
                return show(config('code.error'), '用户已追问/申诉，请重新加载页面');
            }
            if (!isset($questionInfo['question_extend']['version']) || Util::CheckAppVersion('2.9.4', $questionInfo['question_extend']['version']) === '小')
            {
                return show(config('code.error'), '该问题不支持补充回复，请重新加载页面');
            }
            if ($addQuestionModel->getQuestionAddQuestionNum($qid, 0) > 0)
            {
                return show(config('code.error'), '用户已追问/申诉，请重新加载页面');
            }
            $answerRule = $questionModel->answerRule($questionInfo['question_type']);
            $asnwerType = 1;
        } else
        {
            // 退回重答
            if ($questionInfo['status'] !== 20)
            {
                return show(config('code.error'), '问题状态异常，请稍后再试～');
            }
            $appealInfo = $zlcrAppealModel->where(['type' => 3, 'qid' => $qid])->order('id desc')->find();
            if ($appealInfo['status'] == 4)
            {
                $answerRule = $questionModel->answerRule($questionInfo['question_type']);
                $asnwerType = 2;
            } elseif ($appealInfo['status'] == 5)
            {
                $answerRule = [
                    'text_min' => 30,
                    'text_max' => 150,
                    'duration_min' => 20,
                    'duration_max' => 300,
                ];
                $asnwerType = 3;
            }
        }
        $answerRule['text_min'] = $answerRule['text_min'] > 50 ? 50 : $answerRule['text_min'];
        if ($type === 1)
        {
            if ($duration < $answerRule['duration_min'])
            {
                return show(config('code.error'), '语音至少录制' . $answerRule['duration_min'] . '秒');
            }
            if ($duration > $answerRule['duration_max'])
            {
                return show(config('code.error'), '语音最多录制' . $answerRule['duration_max'] . '秒');
            }
        } else
        {
            if (mb_strlen($content) < $answerRule['text_min'])
            {
                return show(config('code.error'), '答案至少' . $answerRule['text_min'] . '字');
            }
            if (mb_strlen($content) > $questionModel->answerRule($questionInfo['question_type'])['text_max'])
            {
                return show(config('code.error'), '答案最多' . $answerRule['text_max'] . '字');
            }
        }

        try
        {

            switch ($asnwerType)
            {
                case 1: // 主动补充回答
                    if ($questionInfo['supplement_answer_num'] >= 1)
                    {
                        return show(config('code.error'), '当前最多只能进行1次补充回答～');
                    }
                    $supplementAnswerData = $questionInfo['supplement_answer'];
                    $supplementAnswerData[] = [
                        'type' => 1,
                        'answer_content' => $content,
                        'answer_duration' => $type === 1 ? $duration : 0,
                        'create_time' => $this->request->time()
                    ];

                    $questionModel->UpdateData($qid, [
                        'is_read' => 0, // 用户未读
                        'supplement_answer' => json_encode($supplementAnswerData, JSON_UNESCAPED_UNICODE),
                        'supplement_answer_num' => $questionInfo['supplement_answer_num'] + 1,   // 增加 自己主动补充回答次数
                        'uid' => $questionInfo['uid'],
                    ]);
                    break;
                case 2: // 退回重答问题
                    if (isset($appealInfo) && $appealInfo)
                    {
                        $zlcrAppealModel->updateData($appealInfo['id'], $taskInfo['astr_id'], $taskInfo['qid'], 3, ['return_answer_status' => 1]);
                    }
                    $supplementAnswerData = $questionInfo['supplement_answer'];
                    $supplementAnswerData[] = [
                        'type' => 2,  // 1=>主动回答   2=>退回重答
                        'answer_content' => $content,
                        'answer_duration' => $type === 1 ? $duration : 0,
                        'create_time' => $this->request->time()
                    ];

                    $questionModel->UpdateData($qid, [
                        'is_read' => 0, // 用户未读
                        'status' => 5,
                        'supplement_answer' => json_encode($supplementAnswerData, JSON_UNESCAPED_UNICODE),
                        'return_answer_num' => $questionInfo['return_answer_num'] + 1,   // 增加 自己主动补充回答次数
                        'complain_status' => 0, // 申诉状态重置为未申诉状态
                        'uid' => $questionInfo['uid'],
                    ]);
                    // 发送 问答完成检测 队列 48小时后回答
                    Util::queuePush('question_answer_question_success_check', ['task_id' => $taskId], 172800);
                    // 追问通知检测 40小时后还未追问
                    Util::queuePush('question_answer_user_add_question_notify', ['qid' => $qid], 144000);
                    break;
                case 3: // 退回重答追问
                    if (isset($appealInfo) && $appealInfo)
                    {
                        $zlcrAppealModel->updateData($appealInfo['id'], $taskInfo['astr_id'], $taskInfo['qid'], 3, ['return_answer_status' => 1]);
                    }
                    $addQuestionInfo = $addQuestionModel->getAddQuestionByLastSuccess($qid);
                    if (!$addQuestionInfo)
                    {
                        return show(config('code.error'), '服务异常，没有退回重答的追问～');
                    }
                    $supplementAnswerData = $addQuestionInfo['supplement_answer'] ? json_decode($addQuestionInfo['supplement_answer'], true) : [];
                    $supplementAnswerData[] = [
                        'type' => 2,  // 1=>主动回答   2=>退回重答
                        'answer_content' => $content,
                        'answer_duration' => $type === 1 ? $duration : 0,
                        'create_time' => $this->request->time()
                    ];
                    // 追问回复
                    $addQuestionModel->UpdateData($qid, $addQuestionInfo['id'], [
                        'supplement_answer' => json_encode($supplementAnswerData, JSON_UNESCAPED_UNICODE)
                    ]);
                    // 更新问题状态至待追问
                    $questionModel->UpdateData($qid, [
                        'status' => 5,
                        'is_read' => 0,
                        'complain_status' => 0, // 申诉状态重置为未申诉状态
                        'return_answer_num' => $questionInfo['return_answer_num'] + 1,   // 增加 自己主动补充回答次数
                        'uid' => $questionInfo['uid'],
                    ]);
                    // 发送 问答完成检测 队列 48小时后结算
                    Util::queuePush('question_answer_question_success_check', ['task_id' => $taskId], 172800);
                    // 追问通知检测 40小时后还未追问
                    Util::queuePush('question_answer_user_add_question_notify', ['qid' => $qid], 144000);
                    break;
                default:
                    return show(config('code.error'), '问题状态异常，请联系客服处理～');
            }
            // 给蹭看用户提示有新回复
            (new Zlcr2QuestionUserView())->questionNewAnswer($qid);
            // 消息中心添加信息
            $messageData = [
                'status' => 0,
                'is_read' => 0,
                'range' => $questionInfo['uid'],
                'type' => 2,
                'reid' => 0,
                'cid' => 4,//
                'title' => '问答回复通知',
                'content' => '你开启的悬赏问答，订单编号：' . $questionInfo['order_num'] . '咨询师已对当前订单内容进行补充，请注意查看，您依然可以在48小时内追问占星师。',// 消息中心跳转地址
                'link' => "question_detail?qid={$qid}&need_auth=0",
                'target' => 'local',
                'create_time' => $this->request->time()
            ];
            (new MessageCenter())->pushMessage($questionInfo['uid'], $messageData);
            $pushData = ['action' => 'extend', 'target' => 'local', 'link' => "question_detail?qid={$qid}&need_auth=0"];
            // PUSH推送报告首页
            (new Push())->pushUserMsg($questionInfo['uid'], '你开启的悬赏问答，订单编号：' . $questionInfo['order_num'] . '咨询师已对当前订单内容进行补充，请注意查看，您依然可以在48小时内追问占星师。', $pushData);
        }
        catch (\Exception $e)
        {
            Log::write('退回重答 回复异常：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error');
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        return show(config('code.success'), '回复成功');
    }

    /**
     * 咨询师 进行中列表
     */
    public function astrTaskList()
    {
        $type = input('type/d', 1);
        $astrModel = new ZlcrAstr();
        $questionModel = new Zlcr2UserQuestion();
        $astrTaskModel = new Zlcr2AstrTasks();
        $addQuestionModel = new Zlcr2UserAddQuestion();
        if ($type === 1)
        {   // 进行中
            $this->request->get(['page' => -1]);
            $taskLists = $astrTaskModel->getListPage($this->astrInfo['id'], 'create_time', ['id', 'qid', 'earning', 'qa_level', 'create_time'], 1);
        } else
        {   // 已完成
            $this->request->get(['page' => 1]);
            $this->request->get(['limit' => 20]);
            $taskLists = $astrTaskModel->getListPage($this->astrInfo['id'], 'update_time', ['id', 'qid', 'earning', 'qa_level', 'create_time'], 2);
        }

        $qids = $taskLists['data'] ? array_column($taskLists['data'], 'qid') : [];
        $taskIdInfo = $taskLists['data'] ? array_column($taskLists['data'], null, 'qid') : [];

        $questionList = $questionModel->batchGetInfoByIds($qids);

        $resData = [];
        $userInfoList = [];
        foreach ($questionList as $qid => $questionItem)
        {
            $userDes = '小行星神秘人';
            $nickname = '匿名用户';
            $avatar = '/test/question_answer/anonymity1.png';
            if ($questionItem['is_anonymity'] !== 1)
            {
                if (isset($userInfoList[$questionItem['uid']]))
                {
                    $userDes = $userInfoList[$questionItem['uid']]['user_des'];
                    $nickname = $userInfoList[$questionItem['uid']]['nickname'];
                    $avatar = $userInfoList[$questionItem['uid']]['avatar'];
                } else
                {
                    $userInfo = (new User())->getUserinfo(['id' => $questionItem['uid']]);
                    if ($userInfo['rid'])
                    {
                        $recode = (new Recode())->getRecode(['id' => $userInfo['rid']]);
                        if ($recode)
                        {
                            $utilModel = new Util();
                            $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                        }
                    }
                    $nickname = $userInfo['nickname'];
                    $avatar = $userInfo['avatar'];
                    $userInfoList[$questionItem['uid']] = [
                        'nickname' => $nickname,
                        'avatar' => $avatar,
                        'user_des' => $userDes
                    ];
                }
            }

            switch ($questionItem['status'])
            {
                case 4:
                    $endTime = $questionItem['astr_receiving_time'] + 3600 - $this->request->time();
                    $endTime = $endTime > 0 ? $endTime : 0;
                    $tip1 = $endTime;
                    $tip2 = '内完成作答';
                    break;
                case 5:
                    $tip1 = '';
                    $tip2 = '等待用户追问';
                    if ($questionItem['supplement_answer_num'] === 0 && $questionItem['return_answer_num'] === 0 && $questionItem['reply_time'] + 3600 > $this->request->time())
                    {
                        if ($questionItem['complain_status'] != 1 && $addQuestionModel->getQuestionAddQuestionNum($qid, 0) === 0)
                        {
                            if (isset($questionItem['question_extend']['version']) && Util::CheckAppVersion('2.9.4', $questionItem['question_extend']['version']) !== '小')
                            {   // 用户提问版本 是2.9.4及以上版本
                                $questionItem['status'] = 25; // 用户可以进行补充回答
                                $tip2 = '允许对回答补充1次';
                            }
                        }
                    }
                    break;
                case 6:
                case 7:
                case 21:
                    if (empty($questionItem['lock_reason']))
                    {
                        $tip1 = '本单收益：';
                        $tip2 = ((float)$taskIdInfo[$qid]['earning']) . '元';
                    } else
                    {
                        $tip1 = '';
                        $tip2 = '扣除收益';
                    }
                    $questionItem['status'] = 7;
                    break;
                case 8:
                    $addQuestionList = $addQuestionModel->getQuestionAddQuestionInfo($qid);
                    $addQuestionInfo = array_pop($addQuestionList);
                    if (!$addQuestionInfo)
                    {
                        break;
                    }
                    $endTime = Util::getToAnswerTime($addQuestionInfo['pay_time']);
                    if ($endTime < 0)
                    {   // 超时
                        $tip1 = '';
                        $tip2 = '已超时';
                    } else
                    {   // 未超时
                        $tip1 = $endTime;
                        $tip2 = '内回复追问';
                    }
                    break;
                case 20: // 退回重答
                    $appealInfo = (new ZlcrAppeal())->where(['type' => 3, 'qid' => $qid, 'status' => ['in', [4, 5]]])->order('id desc')->find();
                    $returnAnswerEndTime = $appealInfo['update_time'] + 21600 - time();
                    if ($returnAnswerEndTime < 0)
                    {
                        // 发送重答超时结算队列
                        Util::queuePush('question_answer_supplement_answer_check', ['appeal_id' => (int)$appealInfo['id'], 'task_id' => (int)$taskIdInfo[$qid]['id']], 5);
                    }
                    $tip1 = $returnAnswerEndTime > 0 ? $returnAnswerEndTime : 0;
                    $tip2 = '倒计时';
                    break;
                default:
                    $tip1 = '';
                    $tip2 = '';
            }

            $proportion = ($astrModel->getAstrQuestionAnswerProportion($taskIdInfo[$qid]['create_time'], $questionItem['question_type'], $taskIdInfo[$qid]['qa_level']) * 100) . '%';
            $successTime = $questionItem['success_time'] ? date('Y-m-d H:i:s', $questionItem['success_time']) : '';
            $addQuestionNum = $addQuestionModel->getQuestionAddQuestionNum($qid, 0);

            $resData[] = [
                'qid' => $qid,
                'proportion' => $proportion,
                'success_time' => $successTime,
                'add_question_num' => $addQuestionNum,
                'nickname' => $nickname,
                'avatar' => $avatar,
                'create_time' => Util::timeToStr($questionItem['consult_time']),
                'user_des' => $userDes,
                'task_id' => (int)$taskIdInfo[$qid]['id'],
                'type' => $questionItem['question_type'],
                'question' => $questionItem['question'],
                'question_des' => $questionItem['question_des'],
                'des1' => $tip1 ?? '',
                'des2' => $tip2 ?? '',
                'status' => $questionItem['status'],
                'earning' => $type === 1 ? $questionModel->getQuestionEarning2($questionItem, $taskIdInfo[$qid]) : (float)$taskIdInfo[$qid]['earning'],// 回答收益 包含追问的预计收益
                'astr_receiving_time' => date('Y-m-d H:i:s', $questionItem['astr_receiving_time']), // 接单时间
            ];
        }

        $msg = '请求成功';
        if (count($resData) === 0)
        {//1=>进行中 2=>已完成
            if (1 === $type)
            {
                $msg = '进行中的数据为空！';
            } else
            {
                $msg = '已完成的数据为空！';
            }

        }
        return show(config('code.success'), $msg, [
            'underway_des' => $astrTaskModel->getUnderwayDes($this->astrInfo['id']),
            'list' => $resData
        ]);
    }

    /**
     * 问题详情
     */
    public function questionInfo()
    {
        $taskId = input('task_id/d', '');

        $astrTaskModel = new Zlcr2AstrTasks();
        $astrModel = new ZlcrAstr();
        $addQuestionModel = new Zlcr2UserAddQuestion();

        $is_manage = false;//是否是 后台查看的问题内容
        $app_type = $this->headers['app-type'];
        if (strpos($app_type, 'manage') !== false && (int)$taskId > 999999999)
        {
            $is_manage = true;
        }

        if ($is_manage)
        {
            $qid = $taskId;
            $taskInfo = null;
        } else
        {
            $taskInfo = $astrTaskModel->getInfoById($taskId);
            if (!$taskInfo || $taskInfo['astr_id'] !== $this->astrInfo['id'])
            {
                if (strpos($app_type, 'manage') === false)
                {//不是后台查看的占星师内容
                    return show(config('code.error'), '服务异常，问题不存在');
                }
            }
            $qid = $taskInfo['qid'];
        }

        $questionModel = new Zlcr2UserQuestion();
        $questionInfo = $questionModel->getInfoById($qid, ['astr_id', 'uid', 'question_type', 'question_extend', 'status', 'astr_receiving_time', 'question', 'question_des', 'consult_time', 'is_anonymity', 'answer_content', 'answer_duration', 'reply_time', 'question_imgs', 'gid', 'activity_discount', 'supplement_answer', 'supplement_answer_num', 'return_answer_num', 'complain_status']);

        if (!$questionModel)
        {
            return show(config('code.error'), '服务异常，问题不存在');
        }

        $userDes = '小行星神秘人';
        if ($questionInfo['is_anonymity'] !== 1)
        {
            $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
            if ($userInfo['rid'])
            {
                $recode = (new Recode())->getRecode(['id' => $userInfo['rid']]);
                if ($recode)
                {
                    $utilModel = new Util();
                    $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                }
            }
        }

        $userNickname = $userInfo['nickname'] ?? '匿名用户';
        $userAvatar = $userInfo['avatar'] ?? '/test/question_answer/anonymity1.png';
        $questionStatus = $questionInfo['status'];
        $questionData = null;
        switch ($questionInfo['question_type'])
        {
            case 1:
                if (isset($questionInfo['question_extend']['recode1']) && $questionInfo['question_extend']['recode1'])
                {
                    $questionData['astro_data'][] = [
                        'nickname' => $questionInfo['question_extend']['recode1']['name'],
                        'avatar' => $questionInfo['question_extend']['recode1']['avatar'],
                        'sex' => $questionInfo['question_extend']['recode1']['type'],
                        'age' => Util::getAgeByBirth($questionInfo['question_extend']['recode1']['year'], $questionInfo['question_extend']['recode1']['month'], $questionInfo['question_extend']['recode1']['day'], 2),
                    ];
                }
                if (isset($questionInfo['question_extend']['recode2']) && $questionInfo['question_extend']['recode2'])
                {
                    $questionData['astro_data'][] = [
                        'nickname' => $questionInfo['question_extend']['recode2']['name'],
                        'avatar' => $questionInfo['question_extend']['recode2']['avatar'],
                        'sex' => $questionInfo['question_extend']['recode2']['type'],
                        'age' => Util::getAgeByBirth($questionInfo['question_extend']['recode2']['year'], $questionInfo['question_extend']['recode2']['month'], $questionInfo['question_extend']['recode2']['day'], 2),
                    ];
                }
                break;
            case 2:
            case 3:
                $questionData = $questionInfo['question_extend'];
                break;
            default:
        }

        $tipDes = [
            'tip' => '',
            'time' => 0,
            'status' => 0,
            'tip1' => '',
            'type' => 1
        ];
        $answerData = null;
        $giveUpData = null;
        $answerRule = $questionModel->answerRule($questionInfo['question_type']) ?? ['text_min' => 100, 'text_max' => 240, 'duration_min' => (Util::isOnline() ? 120 : 12), 'duration_max' => 300];
        if ($taskInfo && $taskInfo['status'] === 3)
        {
            $addQuestion = null;
            $hintDes = '已弃答';
        } elseif ($taskInfo && $taskInfo['status'] === 5)
        {
            $tipDes = [
                'tip' => '',
                'time' => 0,
                'status' => 0,
                'tip1' => '',
                'type' => 1
            ];
            $addQuestion = null;
            $hintDes = '回复超时,任务已取消';
        } else
        {
            if ($questionInfo['status'] === 4)
            {   // 问题待解答
                $endTime = $questionInfo['astr_receiving_time'] + 3600 - $this->request->time();
                $endTime = $endTime > 0 ? $endTime : 0;
                $goodInfo = Util::getZhunleQuestionAnswerConfig();
                $oldPrice = (float)(sprintf('%.2f', $goodInfo[$questionInfo['gid']]['price'] * $astrModel->getAstrQuestionAnswerProportion($taskInfo['create_time'], $questionInfo['question_type'], $taskInfo['qa_level'])));
                $price = (float)(sprintf("%.2f", $oldPrice * $questionInfo['activity_discount']));
                // 扣除手续费及营业税费
                $price = Util::getAfterTaxAmount($price);
                $hintBottomBuyBar = '完成作答且通过抽查可得' . $price . '元';
                // 接单5分钟内
                if ($questionInfo['astr_receiving_time'] + 300 > $this->request->time())
                {
                    // 获取已弃答次数
                    $discardNum = $astrTaskModel->getAstrDiscardQuestionNumByToday($this->astrInfo['id']);
                    $giveUpData = [
                        'all_num' => 3,
                        'left_num' => $discardNum,
                        'hint' => '3天内弃答超10次冻结接单资格3天，',
                        'toast' => '如果3天内，弃答超10次，所有问答接单资格将被冻结3日，当前已弃答' . $discardNum . '次。',
                    ];
                }

                $tipDes = [
                    'tip' => '规定回答时间还剩：',
                    'time' => $endTime,
                    'status' => 1,
                    'tip1' => '问题回复超时，已取消',
                    'type' => 1
                ];
            } elseif ($questionInfo['status'] === 8)
            {   // 追问待解答
                $hintBottomBuyBar = '回复追问';
                $answerRule = [
                    'text_min' => 30,
                    'text_max' => 150,
                    'duration_min' => 20,
                    'duration_max' => 300,
                ];
            } elseif ($questionInfo['status'] === 5)
            {
                $tipDes = [
                    'tip' => '等待用户追问',
                    'time' => 0,
                    'status' => 0,
                    'tip1' => '',
                    'type' => 1
                ];
                if ($questionInfo['complain_status'] === 0 && $questionInfo['reply_time'] + 3600 > $this->request->time() && empty($questionInfo['supplement_answer']))
                {
                    // 未被申诉过  且  回答后一小时以内  且 为进行过任何补充回答
                    if (isset($questionInfo['question_extend']['version']) && Util::CheckAppVersion('2.9.4', $questionInfo['question_extend']['version']) !== '小')
                    {   // 用户版本2.9.4版本及以上 且没有追问的订单
                        if ($addQuestionModel->getQuestionAddQuestionNum($qid) === 0)
                        {
                            // 可进行 补充回复
                            $status25Des = '仅允许补充一次，非强制要求';
                            $questionStatus = 25;
                            $answerRule['text_min'] = $answerRule['text_min'] > 50 ? 50 : $answerRule['text_min'];
                            $hintBottomBuyBar = '补充回答';
                        }
                    }
                }

            } elseif ($questionInfo['status'] === 6)
            {
                $tipDes = [
                    'tip' => '任务已完成',
                    'time' => 0,
                    'status' => 0,
                    'tip1' => '',
                    'type' => 1
                ];
            }

            if ($questionInfo['answer_content'])
            {
                $answerData[] = [
                    'nickname' => $this->astrInfo['nickname'],
                    'avatar' => $this->astrInfo['avatar'],
                    'create_time' => Util::timeToStr($questionInfo['reply_time']),  // 回复时间
                    'content' => $questionInfo['answer_content'],
                    'duration' => $questionInfo['answer_duration'],
                    'type_des' => '回答'
                ];
                if ($questionInfo['supplement_answer'])
                {
                    foreach ($questionInfo['supplement_answer'] as $supplementAnswerItem)
                    {
                        $answerData[] = [
                            'nickname' => $this->astrInfo['nickname'],
                            'avatar' => $this->astrInfo['avatar'],
                            'create_time' => Util::timeToStr($supplementAnswerItem['create_time']),  // 回复时间
                            'content' => $supplementAnswerItem['answer_content'],
                            'duration' => $supplementAnswerItem['answer_duration'],
                            'type_des' => $supplementAnswerItem['type'] === 1 ? '补充回答' : '申诉补充回答'
                        ];
                    }
                }
            }
            $addQuestionList = $addQuestionModel->getQuestionAddQuestionInfo($qid);

            $addQuestionData = [];
            $addQuestionSatatus = [
                2 => 1,
                4 => 1,
                5 => 2,
                6 => 3,
            ];
            foreach ($addQuestionList as $addQuestionItem)
            {
                if (in_array($addQuestionItem['status'], [7, 8], true))
                {
                    continue;
                }
                $addQuestionAnswerData = [];
                if ($addQuestionItem['reply_type'] === 1 && $addQuestionItem['status'] === 4)
                {
                    $addQuestionAnswerData[] = [
                        'nickname' => $this->astrInfo['nickname'],
                        'avatar' => $this->astrInfo['avatar'],
                        'create_time' => Util::timeToStr($addQuestionItem['reply_time']),  // 回复时间
                        'content' => $addQuestionItem['answer_content'],
                        'duration' => $addQuestionItem['answer_duration'],
                        'type_des' => ''
                    ];
                    if (isset($addQuestionItem['supplement_answer']))
                    {
                        foreach ($addQuestionItem['supplement_answer'] as $addQuestionSupplementAnswerItem)
                        {
                            $addQuestionAnswerData[] = [
                                'nickname' => $this->astrInfo['nickname'],
                                'avatar' => $this->astrInfo['avatar'],
                                'create_time' => Util::timeToStr($addQuestionSupplementAnswerItem['create_time']),  // 回复时间
                                'content' => $addQuestionSupplementAnswerItem['answer_content'],
                                'duration' => $addQuestionSupplementAnswerItem['answer_duration'],
                                'type_des' => '申诉追问补充：'
                            ];
                        }
                    }
                }

                $addQuestionData[] = [
                    'id' => $addQuestionItem['id'],
                    'nickname' => $userNickname,
                    'avatar' => $userAvatar,
                    'create_time' => Util::timeToStr($addQuestionItem['pay_time']),
                    'question' => $addQuestionItem['question'],
                    'status' => $addQuestionSatatus[$addQuestionItem['status']],
                    'status_des' => $addQuestionSatatus[$addQuestionItem['status']] === 2 ? '该追问已取消' : '',
                    'answer_data' => $addQuestionAnswerData
                ];

                if ($addQuestionItem['status'] === 2)
                {   // 待解答
                    $endTime = Util::getToAnswerTime($addQuestionItem['pay_time']);
                    if ($endTime < 0)
                    {   // 超时
                        $tipDes = [
                            'tip' => '追问回复已超时：',
                            'time' => $endTime * -1,
                            'status' => 2,
                            'tip1' => '',
                            'type' => 1
                        ];
                    } else
                    {   // 未超时
                        $tipDes = [
                            'tip' => '追问回复时间还剩：',
                            'time' => $endTime,
                            'status' => 1,
                            'tip1' => $addQuestionItem['order_num'] ? '追问回复超时，已取消' : '追问回复已超时',
                            'type' => $addQuestionItem['order_num'] ? 1 : 2
                        ];
                    }
                }

                if ($addQuestionItem['status'] === 6 || $addQuestionItem['reply_type'] === 2)
                {   // 后台介入
                    $hintDes2 = '追问回复超时，任务收益已扣除。';
                    $tipDes = [
                        'tip' => '追问回复已超时',
                        'time' => 0,
                        'status' => 0,
                        'tip1' => '',
                        'type' => 1
                    ];
                    continue;
                }
            }
            $addQuestionEarning = $taskInfo ? $questionModel->getAddquestionEarning($questionInfo['gid'], $taskInfo['qa_level'], $taskInfo['create_time']) : $questionModel->getAddquestionEarning($questionInfo['gid'], 1, 0);
            $addQuestion = [
                'hint' => '用户收到回复后48小时内可追问，预估每条' . $addQuestionEarning . '元',    //
                'list' => $addQuestionData
            ];

            if ($taskInfo && ($taskInfo['status'] === 4 || $taskInfo['status'] === 7))
            {
                $appealInfo = (new ZlcrAppeal())->where(['type' => 3, 'qid' => $qid])->order('id desc')->find();
                $hintDes2 = '回答被用户申诉，平台已判定回答违规，如有疑问请联系官方';
                if ($appealInfo['astr_msg'])
                {
                    $hintDes2 .= "\r\n判断理由：" . $appealInfo['astr_msg'];
                }
                $tipDes = [
                    'tip' => '任务已结束',
                    'time' => 0,
                    'status' => 0,
                    'tip1' => '',
                    'type' => 1
                ];
            }

            if ($taskInfo && $taskInfo['status'] === 2 && $taskInfo['lock_earning'] === 1)
            {
                $hintDes2 = '本任务收益已扣除，如有疑问请联系官方';
                $tipDes = [
                    'tip' => '任务已结束',
                    'time' => 0,
                    'status' => 0,
                    'tip1' => '',
                    'type' => 1
                ];
            }

            if ($questionInfo['status'] === 20)
            {
                // 退回重答
                $appealInfo = (new ZlcrAppeal())->where(['type' => 3, 'qid' => $qid])->order('id desc')->find();
                if ($appealInfo['status'] == 4)
                {
                    // 答案重答
                    $hintBottomBuyBar = '申诉回答补充';
                } else
                {
                    // 补充重答
                    $answerRule = [
                        'text_min' => 30,
                        'text_max' => 150,
                        'duration_min' => 20,
                        'duration_max' => 300,
                    ];
                    $hintBottomBuyBar = '申诉追问补充';
                }
                $returnAnswerEndTime = $appealInfo['update_time'] + 21600 - time();
                $hintDes3 = '本次内容补充时间剩余：' . Sec2Time($returnAnswerEndTime);
                if ($appealInfo['astr_msg'])
                {
                    $hintDes3 .= "\r\n补充建议：" . $appealInfo['astr_msg'];
                }
                $hintGiveUpComplainSupplement = '放弃重答会使订单进入退款流程，本单收益将流失。是否确认放弃？';
            }
            if ($questionInfo['status'] === 21)
            {
                $questionStatus = 7;
            }
        }

        $resData = [
            'nickname' => $userNickname,
            'avatar' => $userAvatar,
            'create_time' => Util::timeToStr($questionInfo['consult_time']),  // 咨询时间
            'user_des' => $userDes,
            'question' => $questionInfo['question'],
            'question_des' => $questionInfo['question_des'],
            'question_type' => $questionInfo['question_type'],
            'status' => $questionStatus,
            'status_25_des' => $status25Des ?? '',
            'question_data' => $questionData,
            'tip_des' => $tipDes,
            'answer_data' => $answerData,
            'add_question' => $addQuestion,
            'answer_rule' => $answerRule,
            'photo_list' => $questionInfo['question_imgs'],
            'hint_des' => $hintDes ?? '',
            'hint_bottom_buy_bar' => $hintBottomBuyBar ?? '',
            'give_up_data' => $giveUpData,
            'hint_des2' => $hintDes2 ?? '',
            'hint_des3' => $hintDes3 ?? '',
            'hint_give_up_complain_supplement' => $hintGiveUpComplainSupplement ?? '', //
            'qid' => $qid
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 放弃重答
     */
    public function discardComplainSupplementAnswer()
    {
        $taskId = input('task_id/d');

        $astrTaskModel = new Zlcr2AstrTasks();
        $zlcrAppealModel = new ZlcrAppeal();
        $questionModel = new Zlcr2UserQuestion();

        if (Util::commentCheck($this->astrInfo['id'], ['task_id' => $taskId, 'action' => '重答弃答'], 10))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }

        $taskInfo = $astrTaskModel->getInfoById($taskId);
        if (!$taskInfo || $taskInfo['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '服务异常，问题不存在');
        }
        if ($taskInfo['status'] !== 1)
        {
            return show(config('code.error'), '任务状态异常，请稍后再试~');
        }

        $questionInfo = $questionModel->getInfoById($taskInfo['qid']);
        if ($questionInfo['status'] !== 20)
        {
            return show(config('code.error'), '任务状态异常，请稍后再试~');
        }

        try
        {
            $appealInfo = $zlcrAppealModel->where(['type' => 3, 'qid' => $taskInfo['qid']])->order('id desc')->find();
            $zlcrAppealModel->updateData($appealInfo['id'], $taskInfo['astr_id'], $taskInfo['qid'], 3, ['return_answer_status' => 2]);
            //问题状态处理
            $questionModel->UpdateData($taskInfo['qid'], ['lock_reason' => '主动放弃退回重答', 'complain_status' => 5, 'status' => 21, 'update_time' => $this->request->time(), 'success_time' => $this->request->time()]);
            //问题订单状态处理
            $orderModel = new Orders();
            $orderModel->UpdateData($questionInfo['order_num'], ['status' => 4, 'update_time' => $this->request->time()], 4);
            $addQuestionLists = (new Zlcr2UserAddQuestion())->getQuestionAddQuestionInfo($questionInfo['id']);
            foreach ($addQuestionLists as $addQuestionItem)
            {
                if ($addQuestionItem['status'] === 4 && $addQuestionItem['order_num'])
                {
                    $orderModel->UpdateData($addQuestionItem['order_num'], ['status' => 4], 4);
                }
            }
            $msgContent = "非常抱歉，由于咨询师的回答未通过人工审核，你的问答订单：{$questionInfo['order_num']}现已判定申诉成立，资金将在7个工作日内原路返还，请注意查收。";
            // 计算本单收益
            $taskEarning = $questionModel->getQuestionEarning($questionInfo, $taskInfo);
            //更新占星师任务状态
            $astrTaskModel->UpdateData($taskId, $taskInfo['astr_id'], ['status' => 7, 'lock_earning' => 1, 'deduct_earning_time' => $this->request->time(), 'update_time' => $this->request->time(), 'earning' => $taskEarning['earning']]);
            //审核通过，添加消息中心
            $msg = [
                'range' => $questionInfo['uid'],
                'type' => 1,
                'cid' => 1,
                'is_read' => 0,
                'title' => '订单取消通知',
                'content' => $msgContent,
                'link' => "question_detail?qid={$questionInfo['id']}&comment_id=0&is_answer_detail=0&need_auth=0",
                'target' => "local",
                'create_time' => $this->request->time()
            ];
            (new MessageCenter())->pushMessage($questionInfo['uid'], $msg);
            // 占星师站内信
            (new ZlcrAstrMessage())->add($questionInfo['astr_id'], [
                'status' => 0,
                'is_read' => 0,
                'astr_id' => $questionInfo['astr_id'],
                'type' => 9, // 默认消息
                'title' => '任务取消通知',
                'content' => "由于您放弃/未及时对任务进行重答，任务{$questionInfo['id']}的收益将被冻结，如有疑问请联系官方。",
                'target' => 'local',
                'link' => '/quiz/answer?task_id=' . $taskId,
                'create_time' => $this->request->time()
            ]);
            $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
            if ($userInfo['tel'])
            {   // 向用户发送消息
                Util::sendHySms([$userInfo['tel']], '', 91373, ['order_id' => $questionInfo['id']]);//申诉成立给用户发短信
            }
        }
        catch (\Exception $e)
        {
            Log::write("占星师 重答弃答失败 错误消息：{$e->getMessage()};FILE:{$e->getFile()};Line:{$e->getLine()}", 'error');
            return show(config('code.error'), '服务异常，请稍后再试~');
        }

        return show(config('code.success'), '操作成功');
    }
}
